import React, { useEffect, useRef, useState } from "react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  useDisclosure,
  Input,
  Select,
  SelectItem,
  Textarea,
} from "@nextui-org/react";
import { showToast } from "../toast";
import { useGlobalState, useHttp } from "@/hooks";
import { copyText } from "@/utils/copy";

type Props = {
  size?:
    | "xs"
    | "sm"
    | "md"
    | "lg"
    | "xl"
    | "2xl"
    | "3xl"
    | "4xl"
    | "5xl"
    | "full";
  openCallback?: Fn;
  closeCallback?: Fn;
  confirmCallback?: Fn;
  cancelBtnText?: string;
  confirmBtnText?: string;
  triggerBtnText?: string;
  mode: "create" | "edit";
  visible?: boolean;
  appId?: number;
  children?: React.ReactNode;
};

const SecretModal: React.FC<Props> = ({
  size = "3xl",
  openCallback,
  closeCallback,
  triggerBtnText,
  confirmCallback,
  cancelBtnText,
  confirmBtnText,
  mode,
  appId,
  children,
  visible,
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const isCreateMode = mode === "create";
  const [secret, setSecret] = useState<string>("");
  const { isLoading, http } = useHttp();

  useEffect(() => {
    if (visible) {
      handleOpenRef.current();
    }
  }, [visible]);

  const handleOpen = async () => {
    if (openCallback) {
      openCallback();
    }
    onOpen();
  };

  const handleOpenRef = useRef(handleOpen);
  handleOpenRef.current = handleOpen;

  const handleClose = () => {
    if (closeCallback) {
      closeCallback();
    }
    onClose();
  };

  const handleConfirm = async () => {
    if (confirmCallback) {
      confirmCallback();
    }

    setTimeout(() => copyText(secret), 2000); // delay to copy text
    showToast("Secret has been Copied to clipboard");

    handleClose();
  };

  const httpRef = useRef(http);
  httpRef.current = http;

  useEffect(() => {
    const getSecret = async () => {
      if (appId) {
        const res = await httpRef.current.get("/api/app/secret", {
          appid: appId,
        });
        if (res?.success) {
          setSecret(res.data.secret);
        }
      }
    };

    getSecret();
  }, [appId]);

  return (
    <div className="create-app-modal">
      {isCreateMode && (
        <Button size="sm" radius="md" color="primary" onClick={handleOpen}>
          {triggerBtnText || "Add"}
        </Button>
      )}
      <Modal size={size} isOpen={isOpen} onClose={handleClose}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                App secret
              </ModalHeader>
              <ModalBody>
                <div className="app-secret">{secret}</div>
                {children}
              </ModalBody>
              <ModalFooter>
                <Button
                  isLoading={isLoading}
                  color="primary"
                  onClick={handleConfirm}
                >
                  {confirmBtnText || (isCreateMode ? "Create" : "Save")}
                </Button>

                {cancelBtnText && (
                  <Button color="primary" variant="flat" onPress={onClose}>
                    {cancelBtnText}
                  </Button>
                )}
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
};

export default SecretModal;
